import { _decorator, Animation, Component, instantiate, math, Node, NodePool, Prefab, Vec3 } from 'cc';
import { myGame } from '../MyGame';
import { Tank } from '../tank/Tank';
import { Player } from '../tank/Player';
import { PLAYER_CONFIG_ID } from '../Const';
const { ccclass, property } = _decorator;

@ccclass('TankManager')
export class TankManager extends Component {
    @property(Prefab)
    public enemyPrefab: Prefab = null

    @property(Prefab)
    public playerPrefab: Prefab = null

    @property([Node])
    public spawnPoints: Node[] = []

    @property(Node)
    public playerPoint: Node = null

    @property(Prefab)
    public effectEnemySpawn: Prefab = null

    public nodePool: NodePool = new NodePool()

    spawnEnemies() {
        if (myGame.genEnemyNum == myGame.maxEnemyNum)
            return

        const configIds = [101, 102]
        const tankNum = this.node.children.length
        if (tankNum < myGame.spawnEnemyNum) {
            const genNum = Math.min(myGame.spawnEnemyNum - tankNum, myGame.maxEnemyNum - myGame.genEnemyNum)
            for (let i = 0; i < genNum; i++) {
                const pos = this.spawnPoints[math.randomRangeInt(0, this.spawnPoints.length)].position
                this.playSpawnEffect(pos, () => {
                    const tank = this.createTank()
                    tank.getComponent(Tank).initWithConfig(configIds[math.randomRangeInt(0, configIds.length)])
                    tank.position = pos
                })
            }
            myGame.genEnemyNum += genNum
        }
    }

    createTank() {
        let node = this.nodePool.get()
        if (!node) {
            node = instantiate(this.enemyPrefab)
        }
        node.parent = this.node
        return node
    }

    pushTank(tank: Node) {
        this.nodePool.put(tank)
    }

    spawnPlayer() {
        if(!myGame.player) {
            const playerTank = instantiate(this.playerPrefab)
            playerTank.parent = this.node
            playerTank.position = this.playerPoint.position
            myGame.player = playerTank.getComponent(Player)
            myGame.player.initWithConfig(PLAYER_CONFIG_ID)
            myGame.player.life = myGame.playerMaxLife
        }
        else {
            this.respawnPlayer()
        }
    }

    respawnPlayer() {
        if (myGame.player) {
            myGame.player.node.parent = this.node
            myGame.player.node.position = this.playerPoint.position
            myGame.player.respawn()
        }
    }

    onDestroy() {
        this.nodePool.clear()
    }

    playSpawnEffect(pos: Vec3, callback:() => void) {
        const effect = instantiate(this.effectEnemySpawn)
        effect.parent = this.node.parent
        effect.position = pos
        effect.getComponent(Animation).clips[0].speed = 0.3
        effect.getComponent(Animation).once(Animation.EventType.FINISHED, () => {
            effect.destroy()
            callback()
        })
    }
}


